/*
 * Copyright (C) 2015 takahirom
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.kogitune.intellij.codeinsight.postfix.templates.surround;

import com.intellij.codeInsight.template.Template;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.codeInsight.template.impl.TextExpression;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.util.InheritanceUtil;
import com.kogitune.intellij.codeinsight.postfix.internal.AbstractRichStringBasedPostfixTemplate;
import com.kogitune.intellij.codeinsight.postfix.utils.AndroidPostfixTemplatesUtils;
import org.jetbrains.annotations.NotNull;

import static com.kogitune.intellij.codeinsight.postfix.utils.AndroidClassName.TEXT_UTILS;

/**
 * Postfix template for android TextUtils class.
 *
 * @author kikuchy
 */
public class TextUtilsIsEmptyTemplate extends AbstractRichStringBasedPostfixTemplate {

    public static final Condition<PsiElement> IS_NON_NULL_STRING = new Condition<PsiElement>() {
        @Override
        public boolean value(PsiElement element) {
            return InheritanceUtil.isInheritor(((PsiExpression) element).getType(), "java.lang.CharSequence") && !AndroidPostfixTemplatesUtils.isAnnotatedNullable(element);
        }
    };

    public TextUtilsIsEmptyTemplate() {
        this("isemp");
    }

    public TextUtilsIsEmptyTemplate(@NotNull String alias) {
        super(alias, "TextUtils.isEmpty(expr)", IS_NON_NULL_STRING);
    }

    @Override
    protected void onTemplateFinished(TemplateManager manager, Editor editor, Template template) {
        // nothing
        // Prevent complete statement
    }

    @Override
    public String getTemplateString(@NotNull PsiElement element) {
        return getStaticPrefix(TEXT_UTILS, "isEmpty", element) + "($expr$)$END$";
    }

    @Override
    protected void addExprVariable(@NotNull PsiElement expr, Template template) {
        template.addVariable("expr", new TextExpression(expr.getText()), false);
    }
}
